<script setup lang="ts">
import { ref, watch } from "vue";
import { StarFilled } from "@element-plus/icons-vue";
import ButtonCo from "./buttons/ButtonCo.vue";
import { getM10L10ApproveDetail, flowReject } from "@/api/apply";
import DataGridApprove from "./DataGridApprove.vue";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import { M10Approve } from "@/api/apply";
import { flowoption } from "@/utils/product";
import ButtonTurn from "./buttons/ButtonTurn.vue";

//獲取數據類型
export interface approveitem {
  material_origina: string;
  material_replacea: string;
  material_product: string;
  replace_reason: string;
  replace_comments: string;
  current_flow: number;
  current_flow_phase: string;
  unit: string;
  amount: number;
  start_time: string;
  end_time: string;
  org_code: string;
}
//表單內容
const approveitems = ref<approveitem[]>([]);
//是否為L10的審核
const flow = ref(0);
//
const flowphase = ref("");
//審核意見
const comments = ref("");
//退回選項可見
const centerDialogVisible = ref(false);
//退回流程
const rebackflow = ref("");
//L20審核-1是否執行替換
const replace_flag = ref('Y')

const props = defineProps(["docid", "ismounted","forwordEnable","nextEnable"]);
const emits = defineEmits(["forword","next","resetdocid"])

//結束時間編輯
function end_timeChange(index: number, row: string) {
  approveitems.value[index].end_time = dayjs(row).format("YYYY-MM-DD");
}
//送出
function save() {
  //L20-1審核需填寫是否執行替換
  if (flow.value === 40) {
    ElMessageBox.confirm(
    '是否需在起始時間執行BOM替換',
    '*****',
    {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    }
  )
    .then(() => {
      replace_flag.value = 'Y'
      send()
    })
    .catch(() => {
      replace_flag.value = 'N'
      send()
    })
  }
  //L20送出，結束日期可為空
  else if(flow.value === 60) {
    let flag = false;
    approveitems.value.forEach((item: approveitem) => {
      if (item.end_time === "") {
        flag = true;
      }
    });
    if (flag) {
      ElMessage.error("結束日期為空，不能送出！")
      return false;
    } else {
      send();
    }
  }
  //其他送出
  else {
    send();
  }
}

//執行送出，根據當前所處流程
function send() {
  let userinfo = {
    docid: props.docid,
    current_flow: flow.value,
    username:
      localStorage.getItem("username") === undefined
        ? ""
        : localStorage.getItem("username")?.toString(),
    approve: "Y",
    comments: comments.value,
    created_time: dayjs().format("YYYY-MM-DD"),
    replace_flag:replace_flag.value
  };
  M10Approve(JSON.stringify(userinfo), JSON.stringify(approveitems.value)).then(
    (res) => {
      if (res) {
        ElMessage.success("送出成功");
        emits('resetdocid')
        //置為空
        comments.value = ""
      }
    }
  );
}
//退回
function reback() {
  centerDialogVisible.value = true;
}
function confirmReback() {
  let backflow: number = flowoption.filter(
    (item) => item.desc === rebackflow.value
  )[0].code;
  if (comments.value === "") {
    ElMessage.error("未填寫審核意見");
    return false;
  }
  let info = {
    docid: props.docid,
    current_flow: flow.value,
    backflow: backflow,
    username:
      localStorage.getItem("username") === undefined
        ? ""
        : localStorage.getItem("username")?.toString(),
    comments: comments.value,
  };
  flowReject(JSON.stringify(info)).then((res) => {
    if (res) {
      ElMessage.success("退回成功");
      emits('resetdocid')
      //置為空
      comments.value = ""
      centerDialogVisible.value = false
    //   location.reload();
    }
  });
}
//為解決子組件先加載父組件後加載數據缺失問題，而使用監聽
watch(
  () => props.ismounted,
  () => {
    if (props.ismounted && props.docid) {
      getM10L10ApproveDetail(props.docid).then((res: any) => {
        //M10
        approveitems.value = []
        let current_flow = res[0].current_flow;
        if (current_flow <= 60) {
          if (res.length > 0) {
            res.forEach((item: any) => {
              approveitems.value.push({
                material_origina: item.material_origina,
                material_replacea: item.material_replacea,
                material_product: item.material_product,
                replace_reason: item.replace_reason,
                replace_comments: item.replace_comments,
                current_flow_phase: item.current_flow_phase,
                unit: item.unit,
                amount: item.amount,
                start_time: dayjs(item.start_time).format("YYYY-MM-DD"),
                end_time: "",
                org_code: item.org_code,
                current_flow: item.current_flow,
              });
              flow.value = item.current_flow;
              flowphase.value = item.current_flow_phase;
            });
          }
        }
        else if (current_flow > 60) {
          res.forEach((item: approveitem) => {
            item.start_time =
              item.start_time === ""
                ? ""
                : dayjs(item.start_time).format("YYYY-MM-DD");
            if (current_flow === 70) {
              item.end_time =
                item.end_time === ""
                  ? ""
                  : dayjs(item.end_time).format("YYYY-MM-DD");
            }
            flow.value = item.current_flow;
            flowphase.value = item.current_flow_phase;
            approveitems.value.push(item);
          });
        }
      });
    }
    else if(props.ismounted && props.docid === ""){
      approveitems.value = []
    }
  }
);

function forword(){
  emits('forword')
}

function next(){
  emits('next')
}
</script>

<template>
  <div class="input-box2" v-if="approveitems.length">
    <el-row class="row">
      <el-col :span="4" class="turn_arrow">
        <ButtonTurn v-if="props.forwordEnable" @click="forword" direction="上一個"></ButtonTurn>
      </el-col>
      <el-col
        :span="16"
        style="margin-top: 0px; padding-top: 0px; text-align: center"
      >
        <el-text>單號：</el-text>
        <el-text style="font-weight: 600">{{ props.docid }}</el-text>
        <el-text style="margin-left: 50px">當前流程：</el-text>
        <el-text style="font-weight: 600">{{
          approveitems[0].current_flow_phase
        }}</el-text>
      </el-col>
      <el-col :span="4" class="turn_arrow">
        <ButtonTurn v-if="props.nextEnable" @click="next" direction="下一個"></ButtonTurn>
      </el-col>
    </el-row>
    <DataGridApprove
      :approveitems="approveitems"
      :flow="flow"
      @end_timeChange="end_timeChange"
    ></DataGridApprove>
    <el-divider>
      <el-icon><star-filled /></el-icon>
    </el-divider>
    <el-row >
      <el-col :span="24">
        <span class="row-text1">審核意見：</span>
        <el-input
          class="row-input"
          v-model="comments"
          :rows="2"
          type="textarea"
          style="width: 750px; float: right"
          placeholder="請輸入"
        />
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <ButtonCo text="送出" @click="save" />
      </el-col>
      <el-col :span="12">
        <ButtonCo text="退回" @click="reback" />
      </el-col>
    </el-row>
    <el-dialog
      v-model="centerDialogVisible"
      title="退回"
      width="500"
      align-center
    >
      <template #footer>
        <el-select v-model="rebackflow" style="margin-bottom: 20px">
          <el-option
            v-for="list in flowoption.filter((item) => item.code < flow)"
            :key="list.code"
            :value="list.desc"
          ></el-option>
        </el-select>
        <ButtonCo text="確定" @click="confirmReback"></ButtonCo>
      </template>
    </el-dialog>
  </div>
  <div class="nodata" v-else>暫無數據</div>
</template>

<style>
.input-box2 {
  width: 900px;
  padding-top: 20px;
  /* font-family: "Courier New", Courier, monospace; */
  line-height: 32px;
  min-height: 600px;
  min-width: 850px;
  max-width: 950px;
  background-color: rgba(255, 255, 255, 0.8);
  box-shadow: 0px 10px 10px 0px rgba(30, 30, 30, 0.7);
  margin: 20px auto;
  min-height: 600px;
  border-radius: 20px;
  overflow: hidden;
}
.el-col .row-text1 {
  width: 110px;
  height: 32px;
  text-align: center;
  /* display: inline-block; */
  /* padding-left: 20px; */
  float: left;
  line-height: 32px;
  /* margin-top: 20px; */
}
.input-box1 .el-col,
.input-box2 .el-col {
  margin-top: 20px;
}
.row-input {
  float: right;
  margin-right: 20px;
}
.nodata {
  width: 100%;
  height: 100%;
  text-align: center;
  vertical-align: middle;
  font-size: 24px;
  color: rgb(51, 49, 49);
  font-weight: 800;
  color: rgb(156, 43, 43);
  padding-top: 200px;
}
.turn_arrow{
    text-align: center;
    vertical-align: middle;
    margin-top: 0px !important;
}
</style>
